package com.gitee.gateway.core.utils;

import io.vertx.ext.web.LanguageHeader;
import io.vertx.ext.web.RoutingContext;

import java.util.Locale;
import java.util.ResourceBundle;

public class Resource {

    public static String get(Locale locale, String key, Object... params) {
        return getResource(locale, "resource", key, params);
    }

    public static String get(RoutingContext context, String key, Object... params) {
        return get(getLocale(context), key, params);
    }

    public static String getResource(Locale locale, String bundle, String key, Object... params) {
        ResourceBundle resource = ResourceBundle.getBundle(bundle, locale);
        return resource.getString(key).formatted(params);
    }

    public static String getResource(RoutingContext context, String bundle, String key, Object... params) {
        return getResource(getLocale(context), bundle, key, params);
    }

    public static Locale getLocale(RoutingContext context) {
        LanguageHeader lh = context.preferredLanguage();
        if (lh != null) {
            String tag = lh.tag();
            String subTag = lh.subtag();
            return new Locale.Builder().setLanguage(tag).setRegion(subTag).build();
        }
        return Locale.SIMPLIFIED_CHINESE;
    }
}
